package com.hundunjiang.ToolsServer.server.Impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hundunjiang.CommonServer.api.CommonResult;
import com.hundunjiang.CommonServer.api.ResultCode;
import com.hundunjiang.CommonServer.server.RedisService;
import com.hundunjiang.ToolsServer.server.PhoneService;
import com.hundunjiang.ToolsServer.utils.MsmConstantUtils;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class PhoneServiceImpl implements PhoneService {

    @Autowired
    private RedisService redisService;

    @Value("${redis.key.expire.regist}")
    private Integer expire;


    public static CommonResult message_init(){
        try{
            /* 必要步骤：
             * 实例化一个认证对象，入参需要传入腾讯云账户密钥对 secretId 和 secretKey
             * 本示例采用从环境变量读取的方式，需要预先在环境变量中设置这两个值
             * 您也可以直接在代码中写入密钥对，但需谨防泄露，不要将代码复制、上传或者分享给他人
             * CAM 密钥查询：https://console.cloud.tencent.com/cam/capi
             */
            Credential cred = new Credential(MsmConstantUtils.SECRET_ID, MsmConstantUtils.SECRET_KEY);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
            return CommonResult.success(client);
        }catch (Exception e){
            e.printStackTrace();
            return CommonResult.failed();
        }
    }

    /**
     * 获取手机验证码(注册)
     * @param phone 手机号
     * @param code 验证码
     */
    @Override
    public CommonResult get_phone_code(String phone, String code) {
        try {
            //判断手机是否为null
            if (StringUtils.isEmpty(phone)) {
                return CommonResult.failed(ResultCode.FAILED,"手机号为空");
            }
            //初始化client
            CommonResult commonResult=PhoneServiceImpl.message_init();
            SmsClient client;
            if (PhoneServiceImpl.message_init().getCode()==200){
                client=(SmsClient)commonResult.getData();
            }else {
                return commonResult;
            }
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
            String[] phoneNumberSet1 = {"+86" + phone};
            req.setPhoneNumberSet(phoneNumberSet1);
            req.setSmsSdkAppid(MsmConstantUtils.APP_ID);
            req.setSign(MsmConstantUtils.SIGN_NAME);
            req.setTemplateID(MsmConstantUtils.RegistCode_ID);

            String[] templateParamSet1 = {code, "5"};
            req.setTemplateParamSet(templateParamSet1);
            // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
            SendSmsResponse resp = client.SendSms(req);
            //获取消息状态
            JSONObject jsonObject = JSON.parseObject(SendSmsResponse.toJsonString(resp).split("\\[")[1].split("\\]")[0]);
            String message = jsonObject.getString("Message");
            String code1 = jsonObject.getString("Code");

            if (code1.equals("Ok")){
                redisService.setkeytime(phone,code,expire, TimeUnit.SECONDS);
                return CommonResult.success(ResultCode.SUCCESS,"发送成功");
            }else {
                return CommonResult.failed(ResultCode.FAILED,message);
            }
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            return CommonResult.failed();
        }
    }

    /**
     * 获取手机验证码(注册)
     * @param phone 手机号
     * @param size MinIO空间大小(默认1GB)
     */
    @Override
    public CommonResult send_regist_success(String phone, String size) {
        try {
            //判断手机是否为null
            if (StringUtils.isEmpty(phone)) {
                return CommonResult.failed(ResultCode.FAILED,"手机号为空");
            }
            //初始化client
            CommonResult commonResult=PhoneServiceImpl.message_init();
            SmsClient client;
            if (PhoneServiceImpl.message_init().getCode()==200){
                client=(SmsClient)commonResult.getData();
            }else {
                return commonResult;
            }
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
            String[] phoneNumberSet1 = {"+86" + phone};
            req.setPhoneNumberSet(phoneNumberSet1);
            req.setSmsSdkAppid(MsmConstantUtils.APP_ID);
            req.setSign(MsmConstantUtils.SIGN_NAME);
            req.setTemplateID(MsmConstantUtils.RegistSuccess_ID);

            String[] templateParamSet1 = {size+"GB"};
            req.setTemplateParamSet(templateParamSet1);
            // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
            SendSmsResponse resp = client.SendSms(req);
            //获取消息状态
            System.out.println(SendSmsResponse.toJsonString(resp).split("\\[")[1].split("\\]")[0]);
            JSONObject jsonObject = JSON.parseObject(SendSmsResponse.toJsonString(resp).split("\\[")[1].split("\\]")[0]);
            String message = jsonObject.getString("Message");
            String code1 = jsonObject.getString("Code");
            if (code1.equals("Ok")){
                return CommonResult.success(ResultCode.SUCCESS,"发送成功");
            }else {
                return CommonResult.failed(ResultCode.FAILED,message);
            }
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            return CommonResult.failed();
        }
    }
}
